package com.itheima.aop;


import com.alibaba.fastjson.JSONObject;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.nio.file.OpenOption;
import java.time.LocalDateTime;
import java.util.Arrays;


@Slf4j   //记录日志
@Aspect   //表明该类是一个切面类
@Component  //表明该类被spring IOC容器
public class LogAspect {
    //注入HttpServletRequest
    @Autowired
    private HttpServletRequest request;

    //注入operateLogMapper
    @Autowired
    private OperateLogMapper operateLogMapper;
    //定义通知类型 为环绕通知
    @Around("@annotation(com.itheima.anno.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        //1.操作人ID
        //获取请求头中的jwt令牌 解析令牌
        String jwt = request.getHeader("token");
        //获取jwt令牌中的自定义对象
        Claims claims = JwtUtils.parseJWT(jwt);
        //获取操作人ID
        Integer operateUser =(Integer) claims.get("id");

        //2.操作时间
        LocalDateTime operateTime = LocalDateTime.now();

        //3.操作类名
        String className = joinPoint.getTarget().getClass().getName();

        //4.操作方法名
        String methodName = joinPoint.getSignature().getName();

        //5.操作方法参数
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);

        /**
         * 获取运行耗时
         */
        //1.获取运行开始时间
        long begin = System.currentTimeMillis();

        //2.运行目标方法
        Object result = joinPoint.proceed();

        //3.获取运行结束时间
        long end = System.currentTimeMillis();

        //6.方法返回值
        String returnValue = JSONObject.toJSONString(result);

        //7.操作耗时
        long costTime = end - begin;


        //8.记录操作日志
        OperateLog operateLog = new OperateLog(null,operateUser,operateTime,className,methodName,methodParams,returnValue,costTime);

        //执行operateLogMapper.insert(operateLog);
        operateLogMapper.insert(operateLog);

        log.info("AOP记录操作日志：{}", operateLog);

        return result;
    }


}
